package org.dwpd.service.board.impl;

import lombok.extern.slf4j.Slf4j;
import org.dwpd.mapper.board.BoardMapper;
import org.dwpd.mapper.user.UserMapper;
import org.dwpd.domain.board.BoardMessage;
import org.dwpd.domain.common.Result;
import org.dwpd.domain.user.UserDTO;
import org.dwpd.service.board.BoardService;
import org.dwpd.utils.UserHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

import static org.dwpd.domain.common.Code.RESULT_CODE_FAIL;

@Slf4j
@Service
public class BoardServiceImpl implements BoardService {

    @Autowired
    private BoardMapper boardMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    public Result addMessage(String comment) {

        // 判断用户是否登录
        UserDTO user = UserHolder.getUser();
        if (user == null) {
            return Result.fail(-2, "用户未登录");
        }
        // 判断用户是否在黑名单中
        Integer flag = userMapper.getUserFlagInBlack(user.getUserId());
        if (flag == 1) {
            return Result.fail(RESULT_CODE_FAIL, "用户已进入黑名单，无法进行留言");
        }
        log.info("[addMessage]添加留言信息：userId:{} comment:{} userImage:{},", user.getUserId(), comment, user.getUserImage());
        boardMapper.addMessage(user.getUserId(), comment, user.getUserImage());
        return Result.success("添加留言成功");
    }

    @Override
    public Result getAllMessage() {

        log.info("[getAllMessage]获取所有留言信息");
        List<BoardMessage> result = boardMapper.getAllMessage();
        if (result == null || result.isEmpty()) {
            return Result.fail(-1, "获取所有留言信息失败");
        }
        return Result.success(result);
    }

    @Override
    public Result deleteMessage(Integer bmId) {

        // 1. 判断用户是否登录
        UserDTO user = UserHolder.getUser();
        if (user == null) {
            return Result.unlogin(-2, "用户未登录");
        }
        Integer userId = user.getUserId();
        // 2. 获取留言信息，并进行判断
        Integer messageUserId = boardMapper.getMessageUserIdById(bmId);
        // 2.1 留言信息不存在，无法删除
        if (messageUserId == null) {
            return Result.fail(-1, "删除留言信息失败");
        }
        // 2.2 当前登录用户非留言信息用户，无法删除
        if (messageUserId != userId) {
            return Result.fail(-1, "当前用户非留言信息用户，无法删除");
        }
        log.info("[deleteMessage] 用户 {} 删除留言信息: {}", userId, bmId);
        Integer upRow = boardMapper.deleteMessage(bmId);
        if (upRow == null || upRow <= 0) {
            return Result.fail(-1, "删除留言信息失败");
        }
        return Result.success("删除留言信息成功");
    }

    @Override
    public Integer getMessageByMessageId(Integer bmId, Integer userId) {

        return boardMapper.getMessageUserIdById(bmId);
    }
}
